import { ElMessage } from "element-plus";
import i18n from "@/locales";
import router from "@/router";
import store from "../store";
import "./bignumber";


//阻止页面滚动
let stopMove = () => {
  let m = (e) => e.preventDefault();
  document.body.style.overflow = "hidden";
  document.addEventListener("touchmove", m, { passive: false });
};
// 开启页面滚动
let move = () => {
  let m = (e) => e.preventDefault();
  document.body.style.overflow = "";
  document.addEventListener("touchmove", m, { passive: true });
};

//// 返回输入的金额添补币种位数后的金额
//   去空格
let cleanupAmount = (amount) => {
  amount += "";
  return amount.replace(/,/g, "").trim();
};
let trimLeadingZeroes = (value) => {
  value = value.replace(/^0+/, "");
  if (value === "") {
    return "0";
  }
  return value;
};

//   返回输入金额添补币种位数后的金额
let parseAmount = (amount = "1", decimal = 18) => {
  if (!amount) return "0";
  amount = amount + "".replace(/(0+)$/g, ""); //转number是为了解决小数位后面还有000的情况
  amount = cleanupAmount(amount); //去空格
  const split = amount.split(".");
  const wholePart = split[0];
  let fracPart = split[1] || "";
  // 如果输入有两个小数点 或者位数超出18位 则抛出错误
  if (split.length > 2) {
    throw new Error(`Cannot parse '${amount}' as bignumber`);
  }
  if (fracPart.length > decimal) {
    fracPart = fracPart.substring(0, 18);
  }
  return trimLeadingZeroes(wholePart + fracPart.padEnd(decimal, "0"));
};

// 舍弃后面数位保留n位小数
let toFixedNum = (num, decimal = 4) => {
  if (num && Number(num)) {
    let newNum = num;
    num = num.toString();
    const index = num.indexOf(".");
    if (index != -1) {
      let numlist = num.split(".");
      if (numlist[1].length > decimal) {
        newNum = numlist[0] + "." + numlist[1].substring(0, decimal);
      }
    }
    return parseFloat(newNum);
  } else {
    return num;
  }
};

// hash隱藏中部字符
let hashFilter = (hash, num = 6) => {
  if (hash && hash.length >= num) {
    return hash.slice(0, num) + "......" + hash.slice(hash.length - num);
  } else {
    return hash;
  }
};

// 数字以千分位分隔
let numFilter = (number) => {
  return number.toString().replace(/\d+/, function (n) {
    // 先提取整数部分
    return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
      return $1 + ",";
    });
  });
};

// 文本複製
let copyData = (data) => {
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(data).then(() => {
      ElMessage.success("复制成功");
    });
  } else {
    // 创建text area
    const textArea = document.createElement("textarea");
    textArea.style.position = "fixed";
    textArea.value = data;

    // 使text area不在viewport，同时设置不可见
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    // this.$message.success('复制成功')
    return new Promise((res, rej) => {
      // 执行复制命令并移除文本框
      ElMessage.success("复制成功");
      document.execCommand("copy") ? res() : rej();
      textArea.remove();
    });
  }
};

// 頁面跳轉
let pageJumps = (url) => {
  router.push(url);
};

// .times 乘法
let accMul = (arg1, arg2) => {
  if (!arg1 || !arg2) {
    return 0;
  }
  const num = new BigNumber(arg1).times(new BigNumber(arg2));
  return num.toFixed();
};

// 获取本地国旗图片
let getLocalImg = (name) => {
  return new URL(
    `../assets/img/flag/${name.replace(/\s*/g, "")}`,
    import.meta.url
  ).href;
};

// 获取本地图片
let getLocalimgImgs = (name) => {
  return new URL(`../assets/img/${name.replace(/\s*/g, "")}`, import.meta.url)
    .href;
};

// 文本去空格
let replaceBlank = (str) => {
  return str.replace(/\s*/g, "");
};

// 时间比较 当前时间是否大于传入时间
let timeComparison = (time) => {
  let nowTime = Date.now(); //当前时间毫秒
  let endTime = 0; //结束毫秒
  if (time) {
    endTime = new Date(time).getTime();
  }
  return nowTime > endTime;
};

// 计算当前瀑布流宽度
let getLazyWidth = () => {
  let clientWidth =
    document.documentElement.clientWidth < 1240
      ? 1240
      : document.documentElement.clientWidth;
  let screenWidth = (clientWidth - 17) * 0.96;
  let maxImgNum = Math.floor(screenWidth / 280);
  let maxLazyWidth = (maxImgNum - 1) * 10 + maxImgNum * 280;
  let lazyWidth;
  if (maxLazyWidth > screenWidth) {
    let imgNum = maxImgNum - 1;
    lazyWidth = (imgNum - 1) * 10 + imgNum * 280;
  } else {
    lazyWidth = maxLazyWidth;
  }
  return lazyWidth;
};

// 数字转换k w
let numToKW = (num) => {
  let str = "";
  if (num > 9999) {
    str = toFixedNum(num / 10000, 1) + "w";
  } else if (num > 999) {
    str = toFixedNum(num / 1000, 1) + "k";
  } else {
    str = num;
  }
  return str;
};

// 描述时长转换 时-分-秒
let formatDuration = (totalSeconds) => {
  let padNumber = (number) => {
    return String(number).padStart(2, '0');
  };
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = Math.floor(totalSeconds % 60);
  const formattedHours = padNumber(hours);
  const formattedMinutes = padNumber(minutes);
  const formattedSeconds = padNumber(seconds);
  if(formattedHours=='00') {
    return `${formattedMinutes}:${formattedSeconds}`;
  }else{
    return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
  }
};


// base64转图像文件
let dataURLtoFile = (dataURL,filename)=>{
  const arr = dataURL.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
};


export {
  dataURLtoFile,
  formatDuration,
  timeComparison,
  getLocalImg,
  getLocalimgImgs,
  stopMove,
  move,
  parseAmount,
  toFixedNum,
  hashFilter,
  numFilter,
  copyData,
  pageJumps,
  accMul,
  replaceBlank,
  getLazyWidth,
  numToKW,

};
